<?php
// yyyy-MM-ddTHH:mm:ssZ
// 2021-01-01T12:00:00Z
//echo date('Y-m-d\TH:i:s\Z');exit;
class AliApi
{

    static $AccessKeyId     = 'LTAI*******g8z';
    static $AccessKeySecret = '8pbb1***********0sIyVzBpQ';
    static $AliHost         = 'https://ocr-api.cn-hangzhou.aliyuncs.com';

    //查询域名
    public static function api($action, $param){
        $param = self::getCommonParams();
        $param['Action']  = $action;
        //$param['DomainName'] = $domain;
        $param['Signature']  = self::getSignature($param);
        echo self::$AliHost . '?'.http_build_query($param);
        var_dump(self::httpCurl(self::$AliHost . '?'.http_build_query($param),'aaa.jpg'));
        //echo $param['Timestamp'];exit;
    }

    //公共参数
    private static function getCommonParams()
    {
        date_default_timezone_set("GMT");
        $data = [
            'Format' => 'JSON',
            'Version' => '2021-07-07',
            'AccessKeyId' => self::$AccessKeyId,
            'SignatureMethod' => 'HMAC-SHA1',
            'Timestamp' => date('Y-m-d\TH:i:s\Z'),//'2021-08-09T08:27:00Z',//,
            //'Timestamp'        => date(DATE_ISO8601),//'2021-08-09T08:27:00Z',//,
            'SignatureVersion' => '1.0',
            'SignatureNonce' => md5(microtime()),
        ];
        return $data;
    }

    private static function percentEncode($str)
    {
        // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    //生成签名
    static function getSignature($parameters)
    {
        // 将参数Key按字典顺序排序
        ksort($parameters);
        // 生成规范化请求字符串
        $canonicalizedQueryString = '';
        foreach($parameters as $key => $value)
        {
            $canonicalizedQueryString .= '&' .self::percentEncode($key)
                . '=' . self::percentEncode($value);
        }
        // 生成用于计算签名的字符串 stringToSign
        $stringToSign = 'POST&%2F&' . self::percentencode(substr($canonicalizedQueryString, 1));
        // 计算签名，注意accessKeySecret后面要加上字符'&'
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, self::$AccessKeySecret . '&', true));
        return $signature;
    }


    /**
     * 模拟请求
     *
     * @param string $url
     * @param array  $query       POST内容
     * @param bool   $withHeader  是否返回头信息
     * @param array  $header      发送头信息
     * @return string
     * @throws Exception
     */
    public static function httpCurl($url, $file, $withHeader = false, $header = [])
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        if ($withHeader) {
            curl_setopt($ch, CURLOPT_HEADER, true);
        }

        if (!empty($file)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: application/json',
                'Content-Type: application/octet-stream',
            ));

            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($file));
        }

        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        $response = curl_exec($ch);
        $errorNo  = curl_errno($ch);

        is_resource($ch) && curl_close($ch);

        if (0 !== $errorNo) {
            throw new \Exception('curl error,errno:'.$errorNo);
        }
        return $response;
    }
}

$ak = '';
$sk = '';
$api = new AliApi;
//$cfile = new CURLFile('aaa.jpg', 'application/octet-stream', $base_file_name);

$api->api('RecognizeTravelCard','aaa');